<template>
  <div class="chat-container">
    <!-- 导航栏  -->
    <van-nav-bar
      @click-left="$router.push('/profile')"
      class="page-navbar"
      fixed
      left-arrow
      title="小智同学"
    />
    <!-- /导航栏 -->
    <!-- 消息列表 -->
    <div
      class="message-list"
      ref="message-list"
    >
      <div
        :class="{ reverse: item.isMe }"
        :key="index"
        class="message-item"
        v-for="(item, index) in messageList"
      >
        <van-image
          :src="item.isMe?userInfo.photo:'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1688883695,2969501912&fm=15&gp=0.jpg'"
          class="avatar"
          fit="cover"
          round
        />
        <div
          class="msg-wrap"
          style="flex: 1;"
        >
          <div class="title">{{ item.msg }}</div>
        </div>
      </div>
    </div>
    <!-- /消息列表 -->

    <!-- 发送消息 -->
    <van-cell-group class="send-message">
      <van-field
        @keyup.enter="sendMessage"
        center
        clearable
        v-model.trim="message"
      >
        <van-button
          @click="sendMessage"
          size="small"
          slot="button"
          type="primary"
        >发送</van-button>
      </van-field>
    </van-cell-group>
    <!-- /发送消息 -->
  </div>
</template>

<script>
import io from "socket.io-client";
import { mapState } from "vuex";
import storage from "../../utils/storage";

export default {
  name: "SmartChat",
  data() {
    return {
      message: "",
      messageList: [{ msg: "欢迎来到小智聊天室啊~" }],
      socket: null
    };
  },

  computed: {
    ...mapState(["userInfo"])
  },

  watch: {
    messageList() {
      this.$nextTick(_ => {
        this.keepBottom();
      });
    }
  },

  created() {
    //读取本地存储数据，最多保留一天
    const message = storage.getItem("MESSAGE");
    if (message) {
      const { create_time, info } = message;
      if (!(Date.now - create_time > 1000 * 60 * 60 * 24)) {
        this.messageList = info;
      }
    }

    //建立和服务器的连接
    this.socket = io("http://ttapi.research.itcast.cn");
    //接受服务器端返回的消息
    this.socket.on("message", _ => {
      this.messageList.push(_);
    });
  },

  mounted() {
    this.$nextTick(_ => {
      this.keepBottom();
    });
  },

  beforeDestroy() {
    storage.setItem("MESSAGE", {
      info: this.messageList,
      create_time: Date.now()
    });
  },

  methods: {
    //发送消息
    sendMessage() {
      if (!this.message.trim()) {
        return;
      }
      const data = {
        msg: this.message,
        timestamp: Date.now(),
        isMe: true
      };
      this.socket.emit("message", data);
      this.message = "";
      this.messageList.push(data);
    },
    keepBottom() {
      this.$refs["message-list"].scrollTop = this.$refs[
        "message-list"
      ].scrollHeight;
    }
  }
};
</script>

<style scoped lang="stylus">
.chat-container
  position absolute
  width 100%
  height 100%
  padding 46px 0 50px 0
  top 0
  left 0
  box-sizing border-box
  background #f5f5f6

  .message-list
    height 100%
    overflow-y scroll

    .message-item
      display flex
      flex-flow row nowrap
      align-items flex-start
      padding 10px

      .msg-wrap
        word-break break-all
        word-wrap break-word

      .title
        display table
        background #e0effb
        border-radius 6px
        font-size 14px
        padding 10px 10px
        margin-right 45px

      .avatar
        width 40px
        height 40px
        margin-right 5px

    .reverse
      flex-direction row-reverse

      .msg-wrap
        display flex
        flex-direction row-reverse

        .title
          margin-right 5px
          margin-left 45px

  .send-message
    position fixed
    bottom 0
    left 0
    right 0
    background #f5f5f6 !important
</style>
